<script setup lang="ts">
import { ref, onActivated, computed } from 'vue';
import { useRoute } from 'vue-router';
import type { OnPage } from '@/composables/useList';
import { goodList } from '@/common/api/hbMarket';
import { useList } from '@/composables/useList';
import listItem from '../components/listItem.vue';
import { useItemWidth } from '../hooks/useItemWidth';

const catename = ref('');
const route = useRoute();
const itemWidth = useItemWidth();

onActivated(() => {
  const cname = (route.query?.catename as string) || '';
  if (catename.value === cname) {
    catename.value = cname;
    onRefreshCurrent();
  } else {
    catename.value = cname;
    onRefresh(true);
  }
  console.log('route: ', catename.value);
});

const server: OnPage = async (listConfig) => {
  const res = await goodList({ ...listConfig, category: catename.value });
  const { list } = res.result;
  console.log('goodList: ', list);
  return list;
};

const { list, loading, finished, error, refreshing, onLoad, onRefresh, onRefreshCurrent } = useList(server);

const waterfall = computed(() => {
  let l1 = [];
  let l2 = [];
  for (const i in list.value) {
    if (parseFloat(i) % 2 === 0) {
      l1.push(list.value[i]);
    } else {
      l2.push(list.value[i]);
    }
  }
  return [l1, l2];
});
</script>
<template>
  <div class="goodList">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        v-model:error="error"
        :finished="finished"
        finished-text="没有更多了"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <div class="flex p-3">
          <div class="flex-1 mr-2">
            <listItem v-for="item in waterfall[0]" :key="item.pid" :item="item" :itemWidth="itemWidth" />
          </div>
          <div class="flex-1">
            <listItem v-for="item in waterfall[1]" :key="item.pid" :item="item" :itemWidth="itemWidth" />
          </div>
        </div>
        <template v-if="finished && !list.length">
          <van-empty />
        </template>
        <!-- 底部安全区 -->
        <div class="van-safe-area-bottom"></div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<style lang="less" scoped>
.goodList {
  min-height: 100%;
  background: #f6f6f6;
  padding-top: 1px;
}
</style>
